<template>
    <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>
            <a href="/">货品管理</a>
        </el-breadcrumb-item>
        <el-breadcrumb-item>货品类型</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 查询部分 -->
    <div style="margin: 30px 3px;padding: 30px;">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
            <el-form-item label="类型编码">
                <el-input v-model="formInline.GoodsTypeCode" placeholder="请输入类型编码" clearable />
            </el-form-item>

            <el-form-item label="类型名称">
                <el-input v-model="formInline.GoodsTypeName" placeholder="请输入类型名称" clearable />
            </el-form-item>

            <el-form-item>
                <el-button type="success" @click="GetGoodsTypeTreeAsync">查询</el-button>
                <el-button type="danger" @click="Reset">重置</el-button>
            </el-form-item>
        </el-form>
    </div>

    <el-button type="success" style="margin-left: 16px" @click="AddGoodsType">
        新增+
    </el-button>

    <!-- 数据显示部分 -->
    <div style="margin: 30px 3px;">
        <el-table :data="tableData" style="width: 100%; margin-bottom: 20px" row-key="id" border
            :default-expand-all="false">
            <el-table-column prop="goodsTypeName" label="货品类型名称" width="180" />
            <el-table-column prop="goodsTypeCode" label="货品类型编码" width="140" />
            <el-table-column prop="sort" label="排序" width="80" />
            <el-table-column prop="goodsTypeStatue" label="状态" width="80">
                <template v-slot="setup">
                    <el-tag v-if="setup.row.goodsTypeStatue == true" type="success">启用</el-tag>
                    <el-tag v-else type="danger">禁用</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="goodsTypeNotes" label="备注" width="380" />
            <el-table-column prop="lastModificationTime" label="更新时间" width="180">
                <template v-slot="setup">
                    <span>{{ setup.row.lastModificationTime.substring(0, 10) }} {{
                        setup.row.lastModificationTime.substring(11, 19) }}</span>
                </template>
            </el-table-column>

            <el-table-column label="操作">
                <template v-slot="setup">
                    <el-button type="primary" style="margin-left: 16px" @click="UpdateGoodsType(setup.row)" size="small">
                        编辑
                    </el-button>
                    <el-button type="danger"  @click="DelGoodsType(setup.row.id)"  size="small">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
    </div>

    <!-- 添加货品类型弹出窗 -->
    <el-drawer v-model="AddTypedrawer" title="" :with-header="false" size="50%" >
        <span style="font-size: 25px;">新增</span><br/><br/>
        <hr/>
        
        <el-input
            v-model="AddGoodsTypeInfo.parentId"
            class="w-60 mb-2"
            placeholder="请选择上级类型"
            style="margin: 30px 3px;"
        />

        <el-tree
            ref="treeRef"
            style="max-width: 600px"
            class="filter-tree"
            :data="tableData"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
             @node-Click="treeNodeClick"
        />

        <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="AddGoodsTypeInfo"
            :rules="rules"
            label-width="auto"
        >
            <el-form-item label="货品类型编码" >
                <el-input v-model="AddGoodsTypeInfo.goodsTypeCode" disabled placeholder="系统自动生成"/>
            </el-form-item>

            <el-form-item label="货品类型名称" prop="goodsTypeName">
                <el-input v-model="AddGoodsTypeInfo.goodsTypeName" />
            </el-form-item>

            <el-form-item label="排序" prop="sort">
                <el-input v-model="AddGoodsTypeInfo.sort" disabled/>
            </el-form-item>

            <el-form-item label="状态" prop="goodsTypeStatue">
                <el-radio-group v-model="AddGoodsTypeInfo.goodsTypeStatue">
                    <el-radio :value="true">启用</el-radio>
                    <el-radio :value="false">禁用</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="备注" prop="goodsTypeNotes">
                <el-input v-model="AddGoodsTypeInfo.goodsTypeNotes" type="textarea" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="UpdatesubmitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="UpdateresetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>


    <!-- 编辑货品类型弹出窗 -->
    <el-drawer v-model="Updatedrawer" title="I am the title" :with-header="false" size="50%">
        <span style="font-size: 25px;">编辑</span><br/><br/>
        <hr/>

        <el-input
            v-model="AddGoodsTypeInfo.parentId"
            class="w-60 mb-2"
            placeholder="请选择上级类型"
            style="margin: 30px 3px;"
        />

        <el-tree
            ref="treeRef"
            style="max-width: 600px"
            class="filter-tree"
            :data="tableData"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
             @node-Click="treeNodeClick"
        />

        <el-form
            ref="ruleFormRef"
            style="max-width: 600px"
            :model="AddGoodsTypeInfo"
            :rules="rules"
            label-width="auto"
        >
            <el-form-item label="货品类型编码" >
                <el-input v-model="AddGoodsTypeInfo.goodsTypeCode" disabled placeholder="系统自动生成"/>
            </el-form-item>

            <el-form-item label="货品类型名称" prop="goodsTypeName">
                <el-input v-model="AddGoodsTypeInfo.goodsTypeName" />
            </el-form-item>

            <el-form-item label="排序" prop="sort">
                <el-input v-model="AddGoodsTypeInfo.sort" disabled/>
            </el-form-item>

            <el-form-item label="状态" prop="goodsTypeStatue">
                <el-radio-group v-model="AddGoodsTypeInfo.goodsTypeStatue">
                    <el-radio :value="true">启用</el-radio>
                    <el-radio :value="false">禁用</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="备注" prop="goodsTypeNotes">
                <el-input v-model="AddGoodsTypeInfo.goodsTypeNotes" type="textarea" />
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="UpdatesubmitForm(ruleFormRef)">
                    保存
                </el-button>
                <el-button @click="UpdateresetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </el-drawer>
</template>



<script lang="ts" setup>
import axios from 'axios';
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import { watch } from 'vue'
import type { TreeInstance } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

//响应式数据
const tableData = ref([{
    id: "",
    goodsTypeCode: "",
    goodsTypeName: "",
    goodsTypeStatue: true,
    goodsTypeNotes: "",
    parentId: "",
    sort: 1,
    createName: "",
    lastModificationTime: "",
    children: [
        {
            id: "",
            goodsTypeCode: "",
            goodsTypeName: "",
            goodsTypeStatue: true,
            goodsTypeNotes: "",
            parentId: "",
            sort: 1,
            createName: "",
            lastModificationTime: "",
            children: []
        }
    ]
}])

//钩子函数
onMounted(() => {
    GetGoodsTypeTreeAsync();
})

//分页参数
const PageInfo = ref({
    PageIndex: 1,
    PageSize: 5,
    TotalCount: 0,
    TotalPage: 0
})

//查询参数
const formInline = ref({
    GoodsTypeCode: "",
    GoodsTypeName: "",
    SkipCount: "",
    MaxResultCount: ""
})
//获取货品类型信息
const GetGoodsTypeTreeAsync = () => {
    axios.get("http://localhost:8080/api/app/goods-type/goods-type-tree",
        {
            params: {
                GoodsTypeCode: formInline.value.GoodsTypeCode,
                GoodsTypeName: formInline.value.GoodsTypeName,
                SkipCount: PageInfo.value.PageIndex,
                MaxResultCount: PageInfo.value.PageSize
            }
        }
    )
        .then(res => {
            tableData.value = res.data.items;
            PageInfo.value.TotalCount = res.data.totalCount;
            PageInfo.value.TotalPage = Math.ceil(PageInfo.value.TotalCount * 1.0 / PageInfo.value.PageSize);
        })
}

//重置按钮
const Reset = () => {
    formInline.value.GoodsTypeCode = "";
    formInline.value.GoodsTypeName = "";
}

    //删除按钮
    const DelGoodsType = (id:string) => {
        ElMessageBox.confirm(
            '确定删除?',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }
        )
        .then(() => {
            axios.delete("http://localhost:8080/api/app/goods-type/" + id + "/goods-type",)
                .then(res => {
                    ElMessage.success("货品类型信息删除成功！");
                    GetGoodsTypeTreeAsync();
                })
                .catch(error => {
                    if (error.response && error.response.status === 403) {
                        const msg = error.response.data?.error?.message || "该货品类型存在子节点，不能删除！";
                        ElMessage.error(msg);
                    } else {
                        ElMessage.error("货品类型信息删除失败！");
                    }
                });
        })
}

//--------------------------------------------------------------------------添加方法----------------------------------------------------------------------------------------------//
//--------------------------------------------------------------------------添加方法----------------------------------------------------------------------------------------------//

const AddTypedrawer = ref(false)

    //添加响应式数据
    const AddGoodsTypeInfo=ref({
        id:"",
        goodsTypeCode:"",
        goodsTypeName: "",
        goodsTypeStatue: true,
        goodsTypeNotes: "",
        parentId: "",
        sort: "",
        createName: "admin",
    })

//添加方法
const AddGoodsType = () => {
    AddTypedrawer.value = true;

    //清除数据
    AddGoodsTypeInfo.value.goodsTypeName = "";
    AddGoodsTypeInfo.value.goodsTypeNotes = "";
    AddGoodsTypeInfo.value.goodsTypeStatue = true;
    AddGoodsTypeInfo.value.parentId = "";
    AddGoodsTypeInfo.value.sort = "";
}


const ruleFormRef = ref<FormInstance>()
const locationOptions = ['Home', 'Company', 'School']

//添加验证
const rules = reactive({
    goodsTypeName: [
        { required: true, message: '请输入货品类型名称', trigger: 'blur' },
    ],
    sort: [
        { required: true, message: '请输入排序', trigger: 'blur' },
    ],
    goodsTypeNotes: [
        { required: true, message: '请输入备注', trigger: 'blur' },
        { max: 50, message: '最多只能输入50字符', trigger: 'blur' },
    ],
})

    //点击按钮
    const submitForm = async (formEl: FormInstance | undefined) => {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (valid) {
                axios.post("http://localhost:8080/api/app/goods-type/goods-type",AddGoodsTypeInfo.value)
                .then(res=>{
                    if(res.data!=null)
                    {
                        ElMessage.success("货品类型添加成功！");
                        AddTypedrawer.value=false;
                        GetGoodsTypeTreeAsync();
                    }
                    else {
                        ElMessage.error("货品类型添加失败！")
                    }
                })
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const options = Array.from({ length: 10000 }).map((_, idx) => ({
    value: `${idx + 1}`,
    label: `${idx + 1}`,
}))

    //--------------------------------------------------------------------------树形控件-----------------------------------------------------------------------------//
    //--------------------------------------------------------------------------树形控件----------------------------------------------------------------------------//

interface Tree {
    [key: string]: any
}

const filterText = ref('')
const treeRef = ref<TreeInstance>()

const defaultProps = {
    children: 'children',
    label: 'goodsTypeName',
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.goodsTypeName.includes(value)
}

    const treeNodeClick=(tableData:any)=>{
        ElMessage.success("您选择的节点是："+tableData.goodsTypeName);
        AddGoodsTypeInfo.value.parentId=tableData.id;
        //AddGoodsTypeInfo.value.goodsTypeName=tableData.goodsTypeName;
    }


    //--------------------------------------------------------------------------修改方法-----------------------------------------------------------------------------//
    //--------------------------------------------------------------------------修改方法----------------------------------------------------------------------------//


    const Updatedrawer=ref(false);

    const UpdateGoodsType=(row:any)=>{
        Updatedrawer.value=true;

        AddGoodsTypeInfo.value.id=row.id,
        AddGoodsTypeInfo.value.goodsTypeName=row.goodsTypeName,
        AddGoodsTypeInfo.value.goodsTypeNotes=row.goodsTypeNotes,
        AddGoodsTypeInfo.value.goodsTypeStatue=row.goodsTypeStatue,
        AddGoodsTypeInfo.value.parentId=row.parentId,
        AddGoodsTypeInfo.value.sort=row.sort
    }

    //点击按钮
    const UpdatesubmitForm = async (formEl: FormInstance | undefined) => {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (valid) {
                axios.put(`http://localhost:8080/api/app/goods-type/${AddGoodsTypeInfo.value.id}/goods-type`, AddGoodsTypeInfo.value)
                .then(res=>{
                    if(res.data!=null)
                    {
                        ElMessage.success("货品类型修改成功！")
                        GetGoodsTypeTreeAsync();
                    }
                    else
                    {
                        ElMessage.error("货品类型修改失败！")
                    }
                })
            } else {
            console.log('error submit!', fields)
            }
        })
    }

    const UpdateresetForm = (formEl: FormInstance | undefined) => {
        if (!formEl) return
        formEl.resetFields()
    }




</script>



<style>
.demo-form-inline .el-input {
    --el-input-width: 220px;
}

.demo-form-inline .el-select {
    --el-select-width: 220px;
}
</style>